package drp.snowbell.util.cfg;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import drp.snowbell.util.file.FileUtility;

public class XStreamConfig implements IXmlConfig {

	@Override
	public void save(Object obj, OutputStream out) throws IOException {
		XStream xstream = new XStream(new DomDriver());
		xstream.toXML(obj, out);
	}

	@Override
	public Object load(InputStream in) throws IOException {
		XStream xstream = new XStream(new DomDriver());
		return xstream.fromXML(in);
	}

	@Override
	public void save(Object obj, String path) throws IOException {
		File fo = FileUtility.getFile(path);
		// 文件不存在,就创建该文件
		if (!fo.exists()) {
			// 先创建文件的目录
			File pFile = fo.getParentFile();
			pFile.mkdirs();
		}
		XStream xstream = new XStream(new DomDriver());
		FileOutputStream fos = new FileOutputStream(fo);
		xstream.toXML(obj, fos);

	}

	@Override
	public Object load(String path) throws IOException {
		File file = FileUtility.getFile(path);
		return load(file);
	}

	@Override
	public Object load(File File) throws IOException {
		XStream xstream = new XStream(new DomDriver());
		FileInputStream fis = new FileInputStream(File);
		return xstream.fromXML(fis);
	}

}
